package com.acme.bankapp.service.bank;

import static com.acme.bankapp.service.bank.BankService.saveBank;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import com.acme.bankapp.domain.bank.*;

import com.acme.bankapp.exceptions.bank.*;

public class BankService {

	public static void addClient(Bank bank, Client client)
			throws ClientExistsException {
		ArrayList<Client> al = bank.getClients();
		for (Client cl : al) {
			if (cl.getName().equals(client.getName())) {
				throw new ClientExistsException(
						"Client with such name already exists");
			}
		}
		bank.setClients(client);
		for (ClientRegisrationListener listener : bank.getListeners()) {
			listener.onClientAdded(client);
		}
		saveBank(bank);
	}

	public static void addAccount(Bank bank, int idClient,
			int... initialValueAndOverDraft) {

		if (initialValueAndOverDraft.length == 1) {
			Account savAcc = new SavingsAccount(initialValueAndOverDraft[0]);
			ArrayList<Client> cl = bank.getClients();
			if (cl.size() < idClient) {
				System.out.println("Wrong format input data");
			} else {
				cl.get(idClient).getAccounts().add(savAcc);
			}
		} else if (initialValueAndOverDraft.length == 2) {
			Account checkAcc = new CheckingAccount(initialValueAndOverDraft[0],
					initialValueAndOverDraft[1]);
			ArrayList<Client> cl = bank.getClients();
			if (cl.size() < idClient) {
				System.out.println("Wrong format input data");
			} else {
				cl.get(idClient).getAccounts().add(checkAcc);
			}
		} else {
			System.out.println("Wrong format input data");
		}
		saveBank(bank);
	}

	public static void printBank(Bank b) {
		ArrayList<Client> cl = b.getClients();
		for (Client client : cl) {
			System.out.println(client.toString() + "\n");
		}
	}

	public static void saveBank(Bank b) {
		try {
			ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
					"c:\\Bank.txt"));
			o.writeObject(b);
			o.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static Bank readBank(){
		Bank b = null;
		try {
			ObjectInputStream o = new ObjectInputStream(new FileInputStream("c:\\Bank.txt"));
			b = (Bank)o.readObject();
			o.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return b;
	}

}
